const db = require("../db");

// 创建用户
const createUser = async (username, email, password) => {
  if (!username || !email || !password) {
    throw new Error("用户名、邮箱和密码不能为空");
  }
  if (password.length < 6) {
    throw new Error("密码长度不能小于6");
  }
  // 查询用户邮箱是否存在
  const user = await findUser(email);
  if (user.length > 0) {
    throw new Error("用户已存在");
  }
  const sql = "INSERT INTO users (username, email, password) VALUES (?, ?, ?)";
  const [results] = await db.query(sql, [username, email, password]);
  return results;
};

// 修改用户信息
const updateUserInfo = async (userInfo, userId) => {
  const { username, birthdate, bio, sex, avatar } = userInfo;
  console.log(userInfo);

  // 都是非必填的参数
  if (!userId) {
    throw new Error("用户ID不能为空");
  }
  const [userData] = await db.query("SELECT * FROM users WHERE id = ?", [
    userId,
  ]);
  const currentUser = userData[0];
  const sql = `
    UPDATE users 
    SET username = ?, birthdate = ?, bio = ?, sex = ?, avatar = ?
    WHERE id = ?
  `;
  const [results] = await db.query(sql, [
    username ?? currentUser.username,
    birthdate ?? currentUser.birthdate,
    bio ?? currentUser.bio,
    sex ?? currentUser.sex,
    avatar ?? currentUser.avatar,
    userId,
  ]);
  return results;
};

// 查询用户（根据用户ID）
const findUserById = async (userId) => {
  if (!userId) {
    throw new Error("用户ID不能为空");
  }
  const sql = "SELECT * FROM users WHERE id = ?";
  const [results] = await db.query(sql, userId);

  const { password, id, ...userInfo } = results[0] || {};
  userInfo.userId = id; // 确保返回的用户信息包含 userId 字段
  return userInfo; // 返回用户信息，不包含密码
};
// 查询用户 （根据邮箱作为查询用户条件）
const findUser = async (email) => {
  const sql = "SELECT * FROM users WHERE email = ?";
  const [results] = await db.query(sql, [email]);
  return results;
};

module.exports = {
  createUser,
  findUser,
  findUserById,
  updateUserInfo,
};
